#include "tabledialog.h"

TableDialog::TableDialog(QWidget *parent) :
    QDialog(parent),
    tableView(new QTableView(this)),
    tableModel(new QStandardItemModel(0, 8, this))
{
    setWindowTitle("实时数据表格");
    resize(800, 400);
    // 移除问号按钮
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    // 设置表格模型
    tableModel->setHorizontalHeaderLabels(
        {"时间", "纬度", "经度", "定位质量", "卫星数量", "水平精度 (HDOP)", "海拔", "大地高"});
    tableView->setModel(tableModel);
    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(tableView);
    setLayout(layout);
}

TableDialog::~TableDialog()
{
    delete tableView;
    delete tableModel;
}

void TableDialog::addData(const QStringList &parsedFields)
{
    if (parsedFields.size() < 8) {
        qDebug() << "Invalid data format, skipping...";
        return;
    }
    QList<QStandardItem *> items;
    for (const QString &field : parsedFields) {
        items.append(new QStandardItem(field));
    }

    tableModel->appendRow(items);

    // 限制表格最多显示 50 行数据
    if (tableModel->rowCount() > 50) {
        tableModel->removeRow(0);
    }
}

void TableDialog::clearData()
{
    tableModel->clear();
    tableModel->setHorizontalHeaderLabels(
        {"时间", "纬度", "经度", "定位质量", "卫星数量", "水平精度 (HDOP)", "海拔", "大地高"});
}
